//
//  YDEditInformationController.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2017/11/14.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "YDEditInformationController.h"
#import "YDEditInformationTopView.h"
#import "YDBankCardModel.h"
#import "YDChooseCityBankView.h"
#import "YDCityChooseView.h"

#import "YDProvinceModel.h"
#import "YDBankModel.h"


#define kProviceText @"请选择省份"
#define kCityText @"请选择城市"
#define kBankText @"请选择银行"

@interface YDEditInformationController ()

//YDEditInformationTopView
@property (nonatomic , weak) YDEditInformationTopView *topView;

//选择银行textfield
@property (nonatomic, strong)YDChooseCityBankView *chooseCityBankView;

//选择银行PickerView
@property (nonatomic, strong)YDCityChooseView *cityPickerView;

//省份 城市 支行 数据源
@property (nonatomic, strong)NSMutableArray *provinceList;
@property (nonatomic, strong)NSMutableArray *cityList;
@property (nonatomic, strong)NSMutableArray *bankList;

//当前的placehoder名
@property (nonatomic, copy)NSString *currenTypeName;


//当前的省份 城市 支行模型
@property (nonatomic, strong)YDProvinceModel *currentProviceM;
@property (nonatomic, strong)YDProvinceModel *currentCityM;
@property (nonatomic, strong)YDBankModel *currentBankM;




@end

@implementation YDEditInformationController

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}


#pragma mark - view life
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"银行卡";
    self.view.backgroundColor = NumberColor(247, 247, 247);
    
    [self dismissKeyBoard];
    
    [self setUpNavButton];
    
    [self topView];
    
    [self chooseCityBankView];
    
    //mine-tijiao
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
 
}


//添加导航栏按钮
-(void)setUpNavButton
{
    UIBarButtonItem *rightItemBtn = [UIBarButtonItem imageWithNormalImage:[UIImage imageNamed:@"mine-tijiao"] hightImage:[UIImage imageNamed:@"mine-tijiao"] addTarget:self action:@selector(rightItemBtnClick)];
    self.navigationItem.rightBarButtonItem = rightItemBtn;
}


- (void)rightItemBtnClick
{
    [self postBankName];
}

#pragma mark - 请求省份列表
- (void)loadProvinceData
{
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetProvincesList WithSuccessBlock:^(NSDictionary *resultDict) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        if ([resultDict[@"code"] integerValue] == 200) {
            
            self.provinceList = [YDProvinceModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            [self addCityPickerViewWithName:kProviceText];
            
        }else
        {
           [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"获取列表失败" isExistNav:YES];
        }
        
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"获取列表失败" isExistNav:YES];
    }];
}

#pragma mark - 请求城市列表
- (void)loadCityData
{

    if (self.currentProviceM == nil) {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage
                                                            text:@"请先选择省份"
                                                      isExistNav:YES];
        return;
    }
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    NSString *url = [NSString stringWithFormat:@"%@%@",@"/areainfo/children/" , self.currentProviceM.areaCode];
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:GETMethod];
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
         [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        DDLog(@"%@",resultDict[@"result"])
        if ([resultDict[@"code"] integerValue] == 200) {
     
            self.cityList = [YDProvinceModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            [self addCityPickerViewWithName:kCityText];
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage text:resultDict[@"message"]
                                                          isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage text:@"获取列表失败"
                                                      isExistNav:YES];
    }];
    
}

#pragma mark -请求支行信息列表
- (void)loadBankData
{
    if (self.currentProviceM == nil) {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage
                                                            text:@"请先选择省份"
                                                      isExistNav:YES];
        return;
    }
    
    if (self.currentCityM == nil  &&  ![NSString isMianCity:self.currentProviceM.areaName]) {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage
                                                            text:@"请先选择城市"
                                                      isExistNav:YES];
        return;
    }
    
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    NSString *url = [NSString stringWithFormat:@"%@%@?%@=%@",@"/cnaps/lists/" , self.currentCityM.areaCode,@"bankCard",self.model.bankCard];
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    
    
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:GETMethod];
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        DDLog(@"%@",resultDict[@"result"])
        if ([resultDict[@"code"] integerValue] == 200) {
            
            self.bankList = [YDBankModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            if (self.bankList.count) {
                [self addCityPickerViewWithName:kBankText];
            }else
            {
                [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                                WithType:NavTipsViewTypeMessage text:@"无支行信息"
                                                              isExistNav:YES];
            }
            
            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage text:resultDict[@"message"]
                                                          isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage text:@"获取列表失败"
                                                      isExistNav:YES];
    }];
}


#pragma mark - 上传支行信息
- (void)postBankName
{
    
    if (!self.currentBankM) {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage text:@"请先完善支行信息"
                                                      isExistNav:YES];
        return;
    }
    ///bindCard/fillBranch/{id}
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];


    NSString *url = [NSString stringWithFormat:@"%@%@",@"/bindCard/fillBranch/",@(self.model.Id)];
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    
    
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:POSTMethod];
    
    [request sessionWithToken:authToken RequestWithDictionary:nil andURLString:baseUrl andBody:[NSString stringWithFormat:@"%@=%@&%@=%@",@"branchName",self.currentBankM.bnkName,@"branchCode",self.currentBankM.cnaps] WithSuccessBlock:^(NSDictionary *resultDict) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        DDLog(@"%@",resultDict[@"result"])
        if ([resultDict[@"code"] integerValue] == 200) {
            
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage text:@"上传支行信息成功！"
                                                          isExistNav:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage text:resultDict[@"message"]
                                                          isExistNav:YES];
        }

    } failBlock:^(NSError *error) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage text:@"上传信息失败"
                                                      isExistNav:YES];
    }];

    
}
/////*******YDEditInformationTopView*******////
-(YDEditInformationTopView *)topView
{
    if (_topView == nil) {
        YDEditInformationTopView *topView = [YDEditInformationTopView editInformationTopViewWithBankCardModel:self.model];
        [self.view addSubview:topView];
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.view);
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(198)));
            }else{
                make.height.equalTo(@(rate750(198)));
            }
        }];
        _topView = topView;
    }
    return _topView;
}

#pragma mark - 选省份城市支行的textfield
-(YDChooseCityBankView *)chooseCityBankView
{
    if (!_chooseCityBankView) {
        _chooseCityBankView = [YDChooseCityBankView new];
       
        _chooseCityBankView.backgroundColor = [UIColor whiteColor];
        _chooseCityBankView.frame = CGRectMake(0, isPhoneX? rateX812(208) : rate750(208), LKScreenW, isPhoneX? rateX812(100) : rate750(100));
        
        [self.view addSubview:_chooseCityBankView];
        
        __weak typeof(self)weself = self;

        [_chooseCityBankView setChooseTextBack:^(ChooseType type) {
            
            switch (type) {
                case Choose_Province:
                    [weself loadProvinceData];
                    break;
                case Choose_City:
                    [weself loadCityData];
                    break;
                case Choose_Bank:
                    [weself loadBankData];
                    break;
                default:
                    break;
            }
        }];
//        [_chooseCityBankView mas_makeConstraints:^(MASConstraintMaker *make) {
//            if (isPhoneX) {
//                make.top.equalTo(self.topView.mas_bottom).offset(rateX812(10));
//                make.height.equalTo(@(rateX812(100)));
//            }else{
//                make.top.equalTo(self.topView.mas_bottom).offset(rate750(10));
//                make.height.equalTo(@(rate750(100)));
//            }
//        }];

    }
    return _chooseCityBankView;
}


#pragma mark - Pickerview
-(void)addCityPickerViewWithName:(NSString *)name
{
    if (_cityPickerView) {
        [_cityPickerView removeFromSuperview];
        _cityPickerView = nil;
    }
    NSMutableArray *chooseNameArray = [NSMutableArray new];
    
    if ([name isEqualToString:kProviceText]) {
        
        if (self.provinceList.count) {
            [self.provinceList enumerateObjectsUsingBlock:^(YDProvinceModel *Model, NSUInteger idx, BOOL * _Nonnull stop) {
                [chooseNameArray addObject:Model.areaName];
            }];
        }
       
    }else if ([name isEqualToString:kCityText])
    {
        if (self.cityList.count) {
            [self.cityList enumerateObjectsUsingBlock:^(YDProvinceModel *Model, NSUInteger idx, BOOL * _Nonnull stop) {
                [chooseNameArray addObject:Model.areaName];
            }];
        }
        
        
    }else if ([name isEqualToString:kBankText])
    {
        if (self.bankList) {
            [self.bankList enumerateObjectsUsingBlock:^(YDBankModel *Model, NSUInteger idx, BOOL * _Nonnull stop) {
                [chooseNameArray addObject:Model.bnkName];
            }];
        }
       
    }
    

   
    _cityPickerView = [YDCityChooseView cityChooseViewWithDataModelArray:chooseNameArray];
  
    _cityPickerView.choseTypeName = name;
    _cityPickerView.currentTextFieldName = _chooseCityBankView.text;
    
   
    __weak typeof(self)weself = self;
    
        [_cityPickerView setConfig:^(NSString *choseName,BOOL isConfirm) {
            
            weself.chooseCityBankView.text = choseName;
            
            //遍历省份
            if ([name isEqualToString:kProviceText]) {
                [weself.provinceList enumerateObjectsUsingBlock:^(YDProvinceModel* obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if( [obj.areaName isEqualToString:choseName])
                    {
                        weself.currentProviceM = obj;
                        *stop = YES;
                    }
                    
                }];
                
               
            }else if ([name isEqualToString:kCityText])
            {
                //遍历城市
                [weself.cityList enumerateObjectsUsingBlock:^(YDProvinceModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if( [obj.areaName isEqualToString:choseName])
                    {
                        weself.currentCityM = obj;
                        *stop = YES;
                    }
                }];
                
            }else if ([name isEqualToString:kBankText])
            {
                //weself.currentBankName = choseName;
                //遍历支行
                [weself.bankList enumerateObjectsUsingBlock:^(YDBankModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if( [obj.bnkName isEqualToString:choseName])
                    {
                        weself.currentBankM = obj;
                        *stop = YES;
                    }
                }];
            }
            

        }];
        [[UIApplication sharedApplication].keyWindow addSubview:_cityPickerView];
}



- (NSMutableArray *)provinceList
{
    if (!_provinceList) {
        _provinceList = [NSMutableArray new];
    }
    return _provinceList;
}
- (NSMutableArray *)cityList
{
    if (!_cityList) {
        _cityList = [NSMutableArray new];
    }
    return _cityList;
}

- (NSMutableArray *)bankList
{
    if (!_bankList) {
        _bankList = [NSMutableArray new];
    }
    return _bankList;
}
@end
